#!/usr/bin/python
# -*- coding:utf-8 -*-
import os.path
import tornado.auth
import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import json
import requests


from tornado.options import define, options
import pymongo
import sys
from helper import DbHelper
from wechat_server import WeChat

reload(sys)
sys.setdefaultencoding('utf8')

# 定义监听的端口
define("port", default=8000, help="run on give server", type=int)

api_key = 'JcLrGkPVv9Z_65NxOEy4XsCidYBYCOTO'
api_secret = 'dkU7vRo5AaFqLveM1En4NFhRQDIkLEzw'


class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r"/", IndexHandler),
            (r"/save", SaveHandler),
            (r"/compare", CompareHandler),
        ]

        settings = dict(
                debug=True,
                template_path=os.path.join(os.path.dirname(__file__), "template"),
        )
        tornado.web.Application.__init__(self, handlers, **settings)


class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("index.html")


class CompareHandler(tornado.web.RequestHandler):
    def post(self):
        # 文件暂存地址
        upload_path = os.path.join(os.path.dirname(__file__), "compare")
        file = self.request.files['file']
        for meta in file:
            filename = meta['filename']
            filepath = os.path.join(upload_path, filename)
            with open(filepath, 'wb') as up:
                up.write(meta['body'])

        url = "https://api-cn.faceplusplus.com/facepp/v3/search"

        filename = file[0]['filename']
        print upload_path
        filepath = os.path.join(upload_path, filename)
        f = open(filepath, 'rb')
        faceset = DbHelper('faceset').find()
        faceset_token = faceset[0]["faceset_token"]

        data = {'api_key': api_key,
                'api_secret': api_secret,
                'faceset_token': faceset_token,
                'return_result_count': '3'
                }
        files = {'image_file': f.read()}
        response = requests.post(url, data=data, files=files)

        print "compare result:  ", response.text

        results = json.loads(response.text)

        if results.has_key('results'):
            result = results['results']
            max=0
            face_token=''
            for item in result:
                print 'score:', item['confidence']
                if max < item['confidence']:
                    max=item['confidence']
                    face_token=item['face_token']
                if item['confidence'] > 60:
                    appId = "wx21bd4b86851af6c7";
                    appSecret = "872e068c17a7d143b226d1c8497b3c22";
                    wt = WeChat(appId, appSecret)
                    # 用户标识openid
                    openid = "oKf90s-eBCGhDkJNDNcx9EIHu6z8"
                    wt.send_message(openid, '已到学校')

            user = DbHelper('users').find_one({'face_token': face_token})
            print user
            self.render("result.html",user=user,score=max)

        else:
            self.write("<script>alert('识别失败')</script>")


class SaveHandler(tornado.web.RequestHandler):
    def saveToken(self, face_token):
        print 'face_token :', face_token
        url = "https://api-cn.faceplusplus.com/facepp/v3/faceset/create"
        data = {'api_key': api_key,
                'api_secret': api_secret,
                'face_tokens': face_token,
                }
        response = requests.post(url, data=data)
        print response.text
        data = json.loads(response.text)
        faceset_token = data["faceset_token"]
        DbHelper('faceset').add({'faceset_token': faceset_token})

    def addToken(self, face_token, faceset_token):
        print face_token
        url = "https://api-cn.faceplusplus.com/facepp/v3/faceset/addface"
        data = {'api_key': api_key,
                'api_secret': api_secret,
                'faceset_token': faceset_token,
                'face_tokens': face_token
                }
        response = requests.post(url, data=data)
        print 'addface ', response.text
        data = json.loads(response.text)
        if data.has_key('error_message'):
            self.write("<script>alert('入库失败')</script>")
            DbHelper("user").remove({'face_token':face_token})

    def post(self):
        # 文件暂存地址
        upload_path = os.path.join(os.path.dirname(__file__), "images")
        file = self.request.files['file']
        name = self.get_argument('name', 'UNKNOW')
        for meta in file:
            filename = meta['filename']
            filepath = os.path.join(upload_path, filename)
            with open(filepath, 'wb') as up:
                up.write(meta['body'])

        url = "https://api-cn.faceplusplus.com/facepp/v3/detect"

        filename = file[0]['filename']
        filepath = os.path.join(upload_path, filename)
        f = open(filepath, 'rb')

        data = {'api_key': api_key,
                'api_secret': api_secret,
                }
        files = {'image_file': f.read()}
        response = requests.post(url, data=data, files=files)

        print response.text
        result = json.loads(response.text)
        # 请求失败
        if result.has_key('error_message'):
            self.write("<script>alert('未检测到人脸')</script>")
            return

        faces = result["faces"]
        if (faces):
            faceset = DbHelper('faceset').find()
            for face in faces:
                data = {'name': name, 'image_url': filepath, 'face_token': face["face_token"]}
                _id = DbHelper('users').add(data)

                if faceset.count() == 0:
                    self.saveToken(face["face_token"])
                else:
                    self.addToken(face["face_token"], faceset[0]["faceset_token"])

        else:
            self.write("<script>alert('未检测到人脸')</script>")


if __name__ == "__main__":
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()
